from sanic import Sanic
import aiomysql
import aioredis
from sanic import response
import asyncio
from product_add_api import SpecificMethoD

SpecificMethod = SpecificMethoD()
import json

from . import bp_product

@bp_product.route("/add_product",methods=['POST',])
async def insert_product_work(request):

    if not request.method == 'POST':

        return response.json({
                'status': -1,
                'errorCode': 1,
                'errorMsg':f"请求方式error,request.method:{request.method}",
                'resultBody':None
            })

    info = request.form

    product_name = info.get("product_name")
    product_image = request.files.get("product_image")
    product_price = info.get("product_price")
    

    if not all([product_name,product_image,product_price]):

        return response.json({
                'status': -1,
                'errorCode': 9,
                'errorMsg':f"缺少参数product_name:{product_name},product_image:{product_image},product_price:{product_price}",
                'resultBody':None
            })

    all_product =await SpecificMethod.select_info(sql="select product_name from product")

    if {'product_name': product_name} in all_product:
        
        return response.json({
                'status': -1,
                'errorCode': 10,
                'errorMsg':f"添加商品失败请检查product_name{product_name}是否已创建",
                'resultBody':None
            })

    with open("static/product_img/{}.jpg".format(product_name), 'wb') as f:

        info = f.write(product_image.body)

        if not info:

            return response.json({
                'status': -1,
                'errorCode': 21,
                'errorMsg':f"添加商品失败请检查product_image:{product_image}格式",
                'resultBody':None
            })

    product_image_url = "/static/product_img/{}".format(product_name)

    work = await SpecificMethod.insert_info(sql="insert into product(product_name,product_image,product_price)values(%s,%s,%s);",args=(product_name,product_image_url,product_price))

    if not work:

        return response.json({
                'status': -1,
                'errorCode': 11,
                'errorMsg':f"添加商品失败请检查product_name:{product_name},product_image:{product_image},product_price:{product_price}格式",
                'resultBody':None
            })

    return response.json({
                'status': 1,
                'errorCode': None,
                'errorMsg':None,
                'resultBody':'添加商品成功'
            })